import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'
import CampusPayment from '@/views/CampusPayment.vue'
import CampusCardRecharge from '@/views/CampusCardRecharge.vue'

const academicRoutes = [
  {
    path: '/academic',
    name: 'Academic',
    component: () => import('@/views/Academic.vue'),
    meta: { 
      title: '学术管理',
      requiresAuth: true,
      permissions: ['STUDENT', 'TEACHER', 'ADMIN']
    }
  },
  {
    path: '/academic/course',
    redirect: '/academic?tab=course',
    meta: { 
      requiresAuth: true,
      permissions: ['STUDENT', 'TEACHER', 'ADMIN']
    }
  },
  {
    path: '/academic/grade',
    redirect: '/academic?tab=grade',
    meta: { 
      requiresAuth: true,
      permissions: ['STUDENT', 'TEACHER', 'ADMIN']
    }
  },
  {
    path: '/academic/warning',
    redirect: '/academic?tab=warning',
    meta: { 
      requiresAuth: true,
      permissions: ['STUDENT', 'TEACHER', 'ADMIN']
    }
  },
  {
    path: '/academic/leave',
    redirect: '/academic?tab=leave',
    meta: { 
      requiresAuth: true,
      permissions: ['STUDENT', 'TEACHER', 'ADMIN']
    }
  },
  {
    path: '/academic/title',
    name: 'TitleApplication',
    component: () => import('@/components/academic/TitleApplication.vue'),
    meta: {
      title: '职称评审',
      requiresAuth: true,
      permissions: ['TEACHER']
    }
  },
  {
    path: '/academic/graduation',
    redirect: '/academic/title',
    meta: {
      requiresAuth: true,
      permissions: ['TEACHER']
    }
  }
]

// 定义常量路由和异步路由
export const constantRoutes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/UserLogin.vue'),
    meta: { title: '用户登录', requiresAuth: false }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { title: '智慧校园门户', requiresAuth: true }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/Dashboard.vue'),
    meta: { title: '个人中心', requiresAuth: true }
  },
  {
    path: '/notice',
    name: 'Notice',
    component: () => import('../views/Notice.vue'),
    meta: { title: '通知公告', requiresAuth: true }
  },
  ...academicRoutes,
  {
    path: '/notice/:id',
    name: 'NoticeDetail',
    component: () => import('../views/NoticeDetail.vue'),
    meta: { title: '公告详情', requiresAuth: true }
  },
  {
    path: '/notice/edit/:id',
    name: 'NoticeEdit',
    component: () => import('../views/NoticeEdit.vue'),
    meta: { title: '编辑公告', requiresAuth: true }
  },
  {
    path: '/services',
    name: 'Services',
    component: () => import('../views/Services.vue'),
    meta: { title: '服务事项', requiresAuth: true }
  },
  {
    path: '/resource',
    name: 'Resource',
    component: () => import('../views/Resource.vue'),
    meta: { title: '资源共享', requiresAuth: true }
  },
  {
    path: '/campuspayment',
    name: 'CampusPayment',
    component: () => import('../views/CampusPayment.vue'),
    meta: { title: '校园缴费', requiresAuth: true }
  },
  {
    path: '/payment/card',
    name: 'CampusCardRecharge',
    component: CampusCardRecharge
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('../views/Admin.vue'),
    meta: { title: '管理后台', requiresAuth: true, roles: ['ADMIN'] }
  },
  {
    path: '/admin/resource',
    name: 'ResourceManage',
    component: () => import('../views/ResourceManage.vue'),
    meta: { 
      title: '资源管理', 
      requiresAuth: true, 
      roles: ['ADMIN'] 
    }
  },
  {
    path: '/logs',
    name: 'LogHistory',
    component: () => import('../views/LogHistory.vue'),
    meta: { title: '历史日志', requiresAuth: true }
  },
  {
    path: '/forbidden',
    name: 'Forbidden',
    component: () => import('@/views/ForbiddenPage.vue'),
    meta: { title: '权限不足', requiresAuth: false }
  },
  {
    path: '/payment',
    name: 'CampusPayment',
    component: CampusPayment
  },
  {
    path: '/payment/card',
    name: 'CampusCardRecharge',
    component: CampusCardRecharge
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

// 需要权限控制的路由
export const asyncRoutes = [
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('../views/Admin.vue'),
    meta: { title: '管理后台', requiresAuth: true, roles: ['ADMIN'] }
  },
  {
    path: '/admin/users',
    name: 'UserManage',
    component: () => import('@/views/UserManage.vue'),
    meta: {
      title: '用户管理',
      requiresAuth: true,
      roles: ['ADMIN', 'TEACHER']
    }
  },
  {
    path: '/permission-test',
    name: 'PermissionTest',
    component: () => import('@/views/PermissionTest.vue'),
    meta: {
      title: '权限测试',
      requiresAuth: true
    }
  },
  {
    path: '/id-test',
    name: 'IdTest',
    component: () => import('@/views/IdTest.vue'),
    meta: {
      title: 'ID测试',
      requiresAuth: true
    }
  },
  {
    path: '/admin/title-application',
    name: 'AdminTitleApplication',
    component: () => import('@/components/academic/AdminTitleApplication.vue'),
    meta: {
      title: '职称评审管理',
      requiresAuth: true,
      roles: ['ADMIN']
    },
  },
  {
    path: '/social',
    name: 'Social',
    component: () => import('@/views/Social.vue'),
    meta: {
      title: '社交互动',
      requiresAuth: true
    }
  },
  {
    path: '/social/class-circle',
    name: 'ClassCircle',
    component: () => import('@/views/ClassCircle.vue'),
    meta: {
      title: '班级圈',
      requiresAuth: true
    }
  },
  {
    path: '/social/interest-community',
    name: 'InterestCommunity',
    component: () => import('@/views/InterestCommunity.vue'),
    meta: {
      title: '兴趣社群',
      requiresAuth: true
    }
  },
  {
    path: '/social/community-posts/:communityId',
    name: 'CommunityPosts',
    component: () => import('@/views/CommunityPosts.vue'),
    meta: {
      title: '社群帖子',
      requiresAuth: true
    }
  },
  {
    path: '/repair',
    name: 'RepairApplication',
    component: () => import('@/views/RepairApplication.vue'),
    meta: {
      title: '维修申请',
      requiresAuth: true
    }
  },
  {
    path: '/repair/manage',
    name: 'RepairManage',
    component: () => import('@/views/RepairManage.vue'),
    meta: {
      title: '维修管理',
      requiresAuth: true,
      roles: ['ADMIN', 'STAFF']
    }
  },
  {
    path: '/forbidden',
    name: 'Forbidden',
    component: () => import('@/views/ForbiddenPage.vue'),
    meta: { title: '权限不足', requiresAuth: false }
  },
  {
    path: '/todo',
    name: 'Todo',
    component: () => import('../views/TodoPage.vue'),
    meta: { title: '待办事项', requiresAuth: true }
  },
  {
    path: '/admin/class-circle-manage',
    name: 'ClassCircleManage',
    component: () => import('../views/ClassCircleManage.vue'),
    meta: { title: '班级圈管理', requiresAuth: true, roles: ['ADMIN'] }
  },
  {
    path: '/admin/interest-community-manage',
    name: 'InterestCommunityManage',
    component: () => import('../views/InterestCommunityManage.vue'),
    meta: { title: '兴趣社群管理', requiresAuth: true, roles: ['ADMIN'] }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

// 合并所有路由
const routes = [...constantRoutes, ...asyncRoutes]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 放行静态资源（如下载材料）
  if (to.path && to.path.startsWith('/uploads/')) {
    next()
    return
  }
  // 设置页面标题
  document.title = to.meta.title || '智慧校园门户'
    
  // 如果是登录页面，直接放行
  if (to.path === '/login') {
    next()
    return
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const token = store.state.user.token
    if (!token) {
      next('/login')
      return
    }
    
    // 检查权限变更（仅在非登录页面时）
    if (to.path !== '/login') {
      try {
        const userInfo = await store.dispatch('user/refreshUserInfo')
        
        // 如果是管理员，并且是从登录页面跳转过来，立即检查待办事项
        const userRole = userInfo ? userInfo.role : null
        if ((userRole === 'ADMIN' || userRole === 'admin') && from.path === '/login') {
          // 首先跳转到Home页面
          if (to.path !== '/home') {
            next('/home')
            return
          }
          
          // 使用延时确保组件已经挂载
          setTimeout(() => {
            try {
              // 触发事件，让Home.vue处理弹窗
              window.dispatchEvent(new CustomEvent('check-admin-todos'))
            } catch (error) {
              console.error('登录后检查待办事项失败:', error)
            }
          }, 1000)
        }
      } catch (error) {
        console.error('权限检查失败:', error)
        // 如果权限检查失败，可能是token过期，跳转到登录页
        if (error.message && (error.message.includes('未登录') || error.message.includes('登录已过期'))) {
          store.dispatch('user/logout').then(() => {
            next('/login')
          })
          return
        }
      }
      
      // 检查角色权限
      if (to.meta.roles && to.meta.roles.length > 0) {
        // 正确获取用户角色信息
        const userInfo = store.state.user.userInfo
        const userRole = userInfo ? userInfo.role : null
        console.log('Route guard - checking role:', userRole, 'required roles:', to.meta.roles)
        
        if (!userRole || !to.meta.roles.includes(userRole)) {
          console.log('Permission denied - user role:', userRole, 'required:', to.meta.roles)
          // 权限不足，跳转到403或首页
          next('/forbidden')
          return
        }
      }
    }
  }
  
  next()
})

export default router 